
package com.eworking.eim.receive;

import org.jivesoftware.smack.packet.Message;

import android.text.TextUtils;

import com.eworking.eim.EIMChatManager;
import com.eworking.eim.message.EIMMessage;
import com.eworking.eim.message.EIMMessageEncoder;
import com.eworking.eim.packet.EIMEncryptPacketExtension;
import com.eworking.eim.user.EIMAccountUtils;
import com.eworking.eim.util.EIMLog;

public class EIMGroupMessageListener extends EIMMessageListener {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMGroupMessageListener.class.getSimpleName();
    
    public EIMGroupMessageListener() {
        super();
    }
    
    @Override
    protected void processMessage(Message message) {
        // 发送接收消息回执
        this.ackMessage(message);
        if (!TextUtils.isEmpty(message.getBody())) {
            // 是否存在重复的消息
            if (!this.isDuplicateMessage(message)) {
                if (message.getFrom().equals(EIMChatManager.getInstance().getCurrentAccount())) {
                    EIMLog.d(_TAG, "忽略发送给自己的群组消息");
                    return;
                }
                EIMMessage eimMessage = EIMMessageEncoder.decryptMessage(message);
                if (message.getExtension(EIMEncryptPacketExtension._NAME, EIMEncryptPacketExtension._NAME_SPACE) != null) {
                    // 设置属性为加密
                    eimMessage.setAttribute(EIMMessage._ATTR_ENCRYPTED, true);
                }
                this.processGroupMessage(message, eimMessage);
            }
        }
        
    }
    
    /**
     * 处理群组消息
     * 
     * @param message
     * @param eimMessage
     */
    private void processGroupMessage(Message message, EIMMessage eimMessage) {
        String JID;
        String from = message.getFrom();
        int i = from.indexOf("/");
        if (i > 0) {
            JID = from.substring(0, i - 1);
        } else {
            EIMLog.d("groupchatlistener", "the message is from muc itself");
            JID = from;
        }
        String groupId = EIMAccountUtils.getGroupIdFromGroupJID(JID);
        eimMessage.setChatType(EIMMessage.ChatType.GroupChat);
        eimMessage.setTo(groupId);
    }
}
